package com.note.simpleshop.module.user.service;
import com.note.simpleshop.entity.TbUser;
import com.note.simpleshop.module.user.auth.TokenManager;
import com.note.simpleshop.module.user.dao.UserRepository;
import com.note.simpleshop.module.user.exception.authc.AccountException;
import com.note.simpleshop.module.user.exception.authc.PasswordException;
import com.note.simpleshop.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TokenManager tokenManager;
    public TbUser findById(String id)
    {
        return userRepository.getOne(id);
    }
    public String login(String username, String password) throws Exception {
        TbUser user = userRepository.findByPhone(username);
        if (user == null) {
            throw new AccountException("用户名或密码不正确");
        } else {
            MD5 md5 = MD5.getInstance();
            logger.info("*******password={},salt={}",password,user.getSalt());
            if (md5.getMD5(password + user.getSalt()).equals(user.getPwd())) {
                String token=tokenManager.generateToken(user.getId());
                return token;
            } else {
                throw new PasswordException("用户名或密码错误");
            }
        }

    }
}